package com.googlecode.todo_robot.frontend.client.util;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.Header;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;

/**
 * @author Fuad Ibrahimov
 * @since 31.12.2009
 */
public class GadgetRpcUtils {

  private GadgetRpcUtils() {
  }

  public static void rpcPost(RequestBuilder requestBuilder) {
    makePostRequest(requestBuilder.getUrl(), requestBuilder.getRequestData(), requestBuilder.getCallback());
  }

  public native static void makePostRequest(String url, String postData, RequestCallback callback) /*-{
  var params = {};
  params[$wnd.gadgets.io.RequestParameters.METHOD] = $wnd.gadgets.io.MethodType.POST;
  //params[$wnd.gadgets.io.RequestParameters.AUTHORIZATION] = $wnd.gadgets.io.AuthorizationType.SIGNED; // AuthorizationType.SIGNED is not supported by Wave container at the moment
  params[$wnd.gadgets.io.RequestParameters.POST_DATA]= postData;
  $wnd.gadgets.io.makeRequest(url, response, params);
  function response(obj) {
    @com.googlecode.todo_robot.frontend.client.util.GadgetRpcUtils::onSuccessInternal(Lcom/googlecode/todo_robot/frontend/client/util/GadgetRpcUtils$GadgetResponse;Lcom/google/gwt/http/client/RequestCallback;)
            (obj, callback);
  }
}-*/;

  public static void onSuccessInternal(final GadgetResponse response, RequestCallback callback) {
  try {
    callback.onResponseReceived(null, new FakeResponse(response));
  } catch (Exception e) {
    callback.onError(null, e);
  }
}

  public static class GadgetResponse extends JavaScriptObject {
    protected GadgetResponse() {
    }

    public final native String getText() /*-{ return this.text; }-*/;
    public final native String[] getErrors()  /*-{ return this.errors;  }-*/;
    public final native String getData() /*-{ return this.data; }-*/;
  }

  public static class FakeResponse extends Response {
    public FakeResponse(GadgetResponse response) {
      this.response = response;
    }

    @Override
    public String getHeader(String s) {
      return null;
    }

    @Override
    public Header[] getHeaders() {
      return new Header[0];
    }

    @Override
    public String getHeadersAsString() {
      return null;
    }

    @Override
    public int getStatusCode() {
      return 200;
    }

    @Override
    public String getStatusText() {
      return "OK";
    }

    @Override
    public String getText() {
      return response.getText();
    }

    private final GadgetResponse response;
  }
}
